package com.acme.bankapp.service.email;

import com.acme.bankapp.domain.email.Email;
import com.acme.bankapp.domain.email.Queue;
import com.acme.bankapp.domain.email.impl.QueueImpl;
import com.acme.bankapp.domain.exceptions.EmptyEmailBoxException;
import com.acme.bankapp.domain.exceptions.MailCantBeAdded;

public class EmailService implements Runnable {

	private Queue <Email> queue;
	
	private static EmailService instance = new EmailService();
	
	public EmailService() {
		queue = new QueueImpl<Email>(5);
		//make a new thread for emailService				
		Thread t = new Thread(this);
		t.start();		
	}

	public static EmailService getEmailService() {
		return instance;
	}
	
	public void sendNotificationEmail (Email email) {
		try {
			queue.addItem(email);
		} catch (MailCantBeAdded e) {
			System.out.println("can't send a mail");
		}
	}

	public void close() {
		queue.close();		
	}

	public void run() { //trying to get email from Queue and "send" it				
		while(!queue.isClosed()){
			try {				
				Email email = queue.getItem();	
				System.out.println(email);
			} catch (EmptyEmailBoxException e) {				
				if (queue.isClosed()) {
					System.out.println("mail service is closed");
				} else {	
					System.out.println("mail service has been interrupted and mail box is empty");
					break;
					}
			}
		}
	}
}
